package model

import (
	"github.com/jinzhu/gorm"
)

type User struct {
	gorm.Model
	Id       string `gorm:"column:_id"`
	Provider string `gorm:"column:provider"`
	Login    string `gorm:"column:login"`
	Password string `gorm:"column:password"`
	Token    string `gorm:"column:token"`
}

func GetUserById(id string) (User, error) {
	var user User
	err := db.Select("provider, login, token").Where("_id = ?", id).First(&user).Error
	if err != nil {
		return user, nil
	}

	return user, err
}

func GetUser(provider string, login string) (User, error) {
	var user User
	err := db.Where("provider = ? AND login = ?", provider, login).First(&user).Error
	return user, err
}

func UpdateUserToken(user User, token string) error {
	err := db.Model(&user).Update("token", token).Error
	return err
}

func GetUserFromToken(token string) (User, error) {
	var user User
	if len(token) == 0 {
		return user, nil
	}

	if err := db.Where("token=?", token).Find(&user).Error; err != nil {
		return User{}, err
	}
	return user, nil
}
